    package com.xteam.xnetworkdisk.utils;

    import com.xteam.xnetworkdisk.constant.Constant;
    import com.xteam.xnetworkdisk.utilsinterface.ChunkFileUtils;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.*;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardCopyOption;
    import java.util.ArrayList;
    import java.util.Set;
    import java.util.regex.Pattern;

    @Component
    @Slf4j
    public class ChunkFileLocalUtils implements ChunkFileUtils {

        private static final String DIRECTORY_PATH = System.getProperty("user.home") + File.separator + "xnetworkdisk";
        private static final String TEMP_PATH = DIRECTORY_PATH + File.separator + "temp";

        @Override
        public void write(String filename, OutputStream thumbnailStream) {
            String newFileName = Tools.sanitizeFileName(filename);

            Path path = Paths.get(TEMP_PATH, newFileName);
            try (InputStream inputStream = new ByteArrayInputStream(((ByteArrayOutputStream) thumbnailStream).toByteArray())) {
                Files.createDirectories(path.getParent()); // Ensure parent directories exist
                Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
                log.info("File written to: {}", path);
            } catch (IOException e) {
                log.error("Error writing file to local storage", e);
            }
        }

        @Override
        public void write(String filename, MultipartFile file) throws IOException {
            String newFileName = Tools.sanitizeFileName(filename);
            Path path = Paths.get(TEMP_PATH, newFileName);
            Files.createDirectories(path.getParent()); // Ensure parent directories exist
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
                log.info("File written to: {}", path);
            } catch (IOException e) {
                log.error("Error writing file to local storage", e);
                throw e; // Re-throw exception after logging
            }
        }

        @Override
        public byte[] read(String filename) {
            String newFileName = Tools.sanitizeFileName(filename);

            Path path = Paths.get(TEMP_PATH, newFileName);
            try {
                return Files.readAllBytes(path);
            } catch (IOException e) {
                log.error("Error reading file from local storage", e);
                return new byte[0]; // Return empty array if an error occurs
            }
        }

        @Override
        public void clearFileUploadCache(String md5Value, int chunks) {

            String baseName = "file:upload:" + md5Value + ":";
            for (int i = 1; i <= chunks; i++) {
                Path path = Paths.get(TEMP_PATH, Tools.sanitizeFileName(baseName + i));
                System.out.println(path);
                try {
                    Files.deleteIfExists(path);
                    log.info("Deleted file: {}", path);
                } catch (IOException e) {
                    log.error("Error deleting file: {}", path, e);
                }
            }

            String videoThumbnail = "file:upload:" + md5Value + ":" + Constant.VIDEO_THUMBNAIL;
            String filename = Tools.sanitizeFileName(videoThumbnail);

            Path path = Paths.get(TEMP_PATH, filename);
            if (path.toFile().exists()) {
                try {
                    Files.deleteIfExists(path);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        public void clearFileUploadCacheArray(String md5Value, Set<Integer> chunks) {

            String baseName = "file:upload:" + md5Value + ":";

            // 遍历 chunks 列表，删除对应的文件
            for (Integer chunkIndex : chunks) {
                Path path = Paths.get(TEMP_PATH, Tools.sanitizeFileName(baseName + chunkIndex));
                System.out.println(path);
                try {
                    Files.deleteIfExists(path);
                    log.info("Deleted file: {}", path);
                } catch (IOException e) {
                    log.error("Error deleting file: {}", path, e);
                }
            }

            String videoThumbnail = "file:upload:" + md5Value + ":" + Constant.VIDEO_THUMBNAIL;
            String filename = Tools.sanitizeFileName(videoThumbnail);

            Path path = Paths.get(TEMP_PATH, filename);

            try {
                Files.deleteIfExists(path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
